from flask import Flask, request
from sqlalchemy import null
from sqlalchemy.exc import SQLAlchemyError
from flask_jwt_extended import JWTManager, decode_token
from flask import Flask

from flask_cors import CORS

from extension import db, cors
import config
import datetime
from models import Account, Book, Category, User, Borrow, Letter, Dialog

#引入蓝图
from users import users_bp
from borrow import borrow_bp
from book import books_bp
from column import column_bp
from bookForm import bookForm_bp
from gpt import gpt_bp

from flask import Blueprint, request
from models import Chat
from openai_api import get_responses_GPT
from extension import db
from sqlalchemy import func


app = Flask(__name__)
app.config.from_object(config)
app.config['SECRET_KEY'] = '123456'
app.config['JWT_SECRET_KEY'] = '!Q@W#E$R'
db.init_app(app)
cors.init_app(app, resources={r"/*": {"origins": "*"}}, method=['GET', 'POST', 'PUT', 'DELETE'], supports_credentials=True)
app.register_blueprint(books_bp)
app.register_blueprint(column_bp)
app.register_blueprint(bookForm_bp)
app.register_blueprint(users_bp, url_prefix='/api/users')
app.register_blueprint(borrow_bp, url_prefix='/api/borrow')
app.register_blueprint(gpt_bp, url_prefix='/api/gpt')

jwt = JWTManager(app)

#拦截器
@app.before_request
def before():
    url = request.path
    print(url)
    #passUrl为最后要用的，开发时使用temporaryUrl
    passUrl = ['/api/users/login','/api/users/register','/api/users/getquestion',
               '/api/users/verifyAnswer','/api/users/updatePwd']
    temporaryUrl = ['/']
    if any(url.startswith(prefix) for prefix in temporaryUrl):
        return None
    else:
        jwt_token = request.headers.get('Authorization')
        if(jwt_token):
            #这里还没有验证是否能验证登录用户，可能有bug
            #检测用户借书日期是否到期限，到期限则进行提醒
            decoded_token = decode_token(jwt_token)
            identity_info = decoded_token['sub']
            user = User.query.filter_by(username=identity_info.get('username')).first()
            if user:
                account = Account.query.filter_by(username=user.username)
                borrow = Borrow.query.filter_by(username=user.username)
                if datetime.date.today() > borrow.endDate:
                    letter = Letter(sender='admin', message='借书期限已到，请及时归还图书', view=0, recipient=user.username,
                                    msgType=0, sendTime=datetime.date.today())
                    db.session.add(letter)
                    db.session.commit()
                return None
            else:
                return {
                    "code": "0",
                    "message": "EXCEPTION"
                }
        else:
            return {
                "code": "0",
                "message": "EXCEPTION"
            }


@app.route('/chat/stream', methods=['GET'])
def ask():
    question = request.json.get('question')
    chatId = request.json.get('chatId')

    promptQuestion = question

    # 获取历史对话
    dialogs = Dialog.query.filter_by(chatid=chatId).order_by(Dialog.id).all()

    # 获取当前最大id，如果没有记录则设为0
    max_order = db.session.query(func.max(Dialog.id)).filter_by(chatid=chatId).scalar()
    if max_order is None:
        max_order = 0

    print("maxOrder")
    print(max_order)

    # 构建历史对话内容
    histories = []
    for dialog in dialogs:
        histories.append({"role": "user", "content": dialog.question})
        histories.append({"role": "assistant", "content": dialog.answer})

    # 获取GPT的响应
    response = get_responses_GPT(promptQuestion, histories)
    if response:
        # 创建新的对话记录
        newDialog = Dialog(id=max_order + 1, chatid=chatId, question=question, answer=response, type=0)
        db.session.add(newDialog)
        db.session.commit()
        return {
            "code": "0",
            "message": "SUCCESS",
            "data": {
                "response": response
            }
        }
    else:
        return {
            "code": "1",
            "message": "ERROR",
            "data": {
                "response": "连接失败，请检查网络连接"
            }
        }

if __name__ == '__main__':
    app.run(port=8080)
